package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.dao.CabinetDao;
import com.wing.cabinet.model.entity.Cabinet;
import com.wing.cabinet.model.entity.CabinetCargoLane;
import com.wing.cabinet.model.request.CabinetForm;
import com.wing.cabinet.model.response.CabinetVO;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.enterprise.feign.EnterpriseClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 刀柜-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CabinetServiceImpl extends ServiceImpl<CabinetDao, Cabinet> implements CabinetService {

    @Autowired
    private EnterpriseClient enterpriseClient;

    @Autowired
    private CellSingleInventoryProductService cellSingleInventoryProductService;

    @Autowired
    private  CellSluggishMaterialsService cellSluggishMaterialsService;

    @Autowired
    private CabinetCargoLaneService cabinetCargoLaneService;



    @Override
    public int add(CabinetForm cabinetForm) {

        //校验

        Cabinet cabinet =new Cabinet();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(Cabinet.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cabinetForm, cabinet, copyOptions);

        return baseMapper.insert(cabinet);
    }

    @Override
    public List<CabinetVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<CabinetVO> inventory(Page page, Map<String, Object> params) {
        List<CabinetVO> list = baseMapper.inventory(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CabinetVO myInventory(String cabCode,String cabinetNature) {
        return baseMapper.myInventory(cabCode,cabinetNature);
    }

    @Override
    public Page<CabinetVO> pageList4app(Page page, Map<String, Object> params) {
        List<CabinetVO> list = baseMapper.list4app(page,params);
        for(CabinetVO item : list){
            if(item.getCabinetNature().getValue() == 0){
                item.setBelongCabinet("-1");
            }/*else{
                item.setCabCode(item.getCode());
            }*/
        }
        /*List<CabinetVO> newList = new ArrayList<>();
        list.stream().forEach(k -> {
            k.setParentId(-1l);
            List<CabinetVO> cabinetList = baseMapper.getCabinetByCabCode(k.getCabCode());
            if(cabinetList.size()>0){
                cabinetList.stream().forEach(s->{
                    s.setParentId(k.getId());
                    newList.add(s);
                });
            }
        });
        if(newList.size()>0){
            newList.stream().forEach(s->{
                list.add(s);
            });
        }*/
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<CabinetVO> pageList4Cab(Page page, Map<String, Object> params) {
        List<CabinetVO> list = baseMapper.list4app(page,params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CabinetVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public CabinetVO get4appByCode(String code) {
        return baseMapper.get4appByCode(code);
    }

    @Override
    public CabinetVO getMainCab4appByCode(String code) {
        return baseMapper.getMainCab4appByCode(code);
    }

    @Override
    public Cabinet getMainCab4appByMainCabCode(String code) {
        return baseMapper.selectOne(new QueryWrapper<Cabinet>().eq("cab_code",code));
    }

    @Override
    @Transactional
    public JsonResult<CabinetVO> isExistAndUpdate(String code,String cabName) {
        CabinetVO cabinetVO = baseMapper.get4appByCode(code);
        if (cabinetVO==null){
            return JsonResult.fail("未找到柜子");
        }
        Cabinet cabinet4Update=new Cabinet();
        cabinet4Update.setId(cabinetVO.getId());
        cabinet4Update.setCabName(cabName);
        baseMapper.updateById(cabinet4Update);
        return JsonResult.success(cabinetVO);
    }

    @Override
    public int updateCompany(Map<String, Object> params) {
        if (params.isEmpty()){
            return 0;
        }
        CabinetVO cabinetVO=baseMapper.get4appById(Long.valueOf(String.valueOf(params.get("id"))));
        if (cabinetVO==null){
            throw new BusinessException("未找到柜子");
        }
        if (Cabinet.CabinetNature.main.equals(cabinetVO.getCabinetNature())){
//            int result = baseMapper.updateCompanyByMain(params);
//            if (result>0){
//                params.put("cabName",null);
//                result = baseMapper.updateCompanyByAuxiliary(params);
//                return  result;
//            }
            params.put("belongCabinet",cabinetVO.getCabCode());
        }else{
            params.put("belongCabinet",cabinetVO.getBelongCabinet());
        }
        baseMapper.updateCompany(params);
        Cabinet cabinet=new Cabinet();
        cabinet.setId(cabinetVO.getId());
        cabinet.setCabName(String.valueOf(params.get("cabName")));
        cabinet.setWorkshopId((Long) params.get("workshopId"));
        cabinet.setRemark(String.valueOf(params.get("remark")));
        //只能修改主柜的车间，辅柜跟着主柜的走，修改主柜时，辅柜也修改车间
        baseMapper.updateWorkshop(String.valueOf(params.get("belongCabinet")),(Long) params.get("workshopId"));
        return baseMapper.updateById(cabinet);
    }

    @Override
    public Cabinet getCabinetVOByCabCode(String cabCode) {
        LambdaQueryWrapper<Cabinet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cabinet ::getCabCode,cabCode);
        Cabinet cabinet = baseMapper.selectOne(wrapper);
        return cabinet;
    }

    @Override
    public List<CabinetVO> getCabinetByCabinetNature() {
        return baseMapper.getCabinetByCabinetNature();
    }

    @Override
    public List<CabinetVO> getCabs() {
        List<CabinetVO> mainCabList=new ArrayList<>();
        Map<String,List<CabinetVO>> subCabMap=new HashMap<>();
        List<CabinetVO> cabinetVOS=baseMapper.list4app(new HashMap<>());

        for (CabinetVO cabinetVO:cabinetVOS){
            if (Cabinet.CabinetNature.main.equals(cabinetVO.getCabinetNature())){
                mainCabList.add(cabinetVO);
            }else{
                List<CabinetVO> tempList=subCabMap.get(cabinetVO.getBelongCabinet());
                if (tempList==null){
                    tempList=new ArrayList<>();
                    tempList.add(cabinetVO);
                    subCabMap.put(cabinetVO.getBelongCabinet(),tempList);
                }else {
                    tempList.add(cabinetVO);
                }
            }
        }
        mainCabList.forEach(e->{
            e.setSubCabs(subCabMap.get(e.getCabCode()));
            Map paramMap=new HashMap();
            paramMap.put("mainCabCode",e.getCabCode());
            e.setQuantityAlarm(cellSingleInventoryProductService.count4Alarm(paramMap));
            e.setQuantitySluggish(cellSluggishMaterialsService.pageList(new Page(),paramMap).getRecords().size());
            e.setSkuNum(cellSingleInventoryProductService.countSkuByMainCabCode(e.getCabCode()));
            e.setLaneNum(cabinetCargoLaneService.countLanesByMainCabCode(e.getCabCode()));
        });
        return mainCabList;
    }
}
